from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.shortcuts import redirect


class UserInfo(object):

    def __init__(self,role,name,id):
        self.id = id
        self.name = name
        self.role = role

class AuthMiddleware(MiddlewareMixin):

    def process_request(self,request):
        """校验用户是否已登录"""
        #1.不需要登录就能访问的URL
        if request.path_info in settings.C_WHITE_URL:
            return

        #session中获取用户信息，能获取到，登录成功；反之，未登录
        user_dict = request.session.get(settings.C_SESSION_KEY)

        #未登录，跳转回登录页面
        if not user_dict:
            return redirect(settings.C_LOGIN_URL)

        #已登录
        request.userinfo = UserInfo(**user_dict)
        # request.userinfo.id
        # request.userinfo.name
        # request.userinfo.role
        print('request中间件：',request.userinfo.name)

        return



    def process_view(self,request,callback,callback_args,callback_kwargs):
        pass